#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

#include "utils.h"

/* load:    load file to buffer
 *
 * file:    filename
 * buf:     output buffer
 * maxsize: read max bytes
 * */

int load(const char *file, char *buf, int maxsize)
{
    int fd = 0;
    fd = open(file, O_RDONLY);
    if (fd < 0) {
        pr_err("open failed: %s, %d.\n", file, fd);
        return fd;
    }

    int len = 0;
    int cnt = 0;
redo:
    len = read(fd, buf + cnt, maxsize - cnt);
    if (len < 0) {
        pr_err("read failed: %s, %d\n", file, len);
        return len;
    }

    cnt += len;
    if (len != 0 && cnt < maxsize)
        goto redo;

    close(fd);
    return cnt;
}

void str_compress(char *buf, char *delim, char replace)
{
    int i, j = 0;
    int in_delim = 0;
    // size_t delim_len = strlen(delim);

    for (i = 0; buf[i] != '\0'; i++) {
        if (strchr(delim, buf[i])) {
            if (!in_delim) {
                buf[j++] = replace;
                in_delim = 1;
            }
        } else {
            buf[j++] = buf[i];
            in_delim = 0;
        }
    }
    buf[j] = '\0';
}

void str_replace(char *buf, char delim, char replace)
{
    while (*buf) {
        if (*buf == delim)
            *buf = replace;
        buf++;
    }
    if (*(buf - 1) == replace)
        *(buf - 1) = '\0';
}
